package com.logistic.server.common.resolver;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.logistic.server.common.constant.Constants;
import com.logistic.server.common.constant.RedisConst;
import com.logistic.server.common.utils.RedisUtils;
import com.logistic.server.common.utils.ServletUtils;
import com.logistic.server.entity.common.WebUserToken;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * 登录信息默添加在参数
 * @author swen
 */
@Component
public class ArgumentResolver implements HandlerMethodArgumentResolver {

    @Resource
    private RedisUtils redis;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().equals(WebUserToken.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) {
        String token = Objects.requireNonNull(ServletUtils.getRequest()).getHeader(Constants.TOKEN);
        if(StrUtil.isNotBlank(token)) {
            return JSONObject.parseObject(redis.get(RedisConst.ACCESS_TOKEN + token), WebUserToken.class);
        }
        return null;
    }
}
